import Socket from "./lib/socket";
import { Config } from "./typing";
import { EventEmitter } from 'events';

const pool: any = {
    serviceConfig: {},
};

export const configEmitter = new EventEmitter();
export const serviceConfigEmitter = new EventEmitter();
export const socket: Socket = new Socket("ws://localhost:1028");

export function getServiceConfig(serviceName: string): Promise<any> {
    return new Promise((resolve) => {
        if (pool.serviceConfig[serviceName]) {
            resolve(pool.serviceConfig[serviceName]);
        } else {
            socket.wsCallback({ type: "getServiceConfig", serviceName }, (config) => {
                pool.serviceConfig[serviceName] = config;
                resolve(config);
            });
        }
    });
}

export function setServiceConfig(serviceName: string, config: any, sendFlag=true) {
    if (config !== pool.serviceConfig[serviceName]) {
        pool.serviceConfig[serviceName] = config;
        if (sendFlag) {
            socket.send({ type: "updateServiceConfig", serviceName, config });
        }
    }
}

export function getConfig(): Promise<Config> {
    return new Promise((resolve) => {
        if (pool.config) {
            resolve(pool.config);
        } else {
            socket.wsCallback({ type: "getConfig" }, (config) => {
                pool.config = config;
                resolve(config);
            });
        }
    });
}

export function setConfig(configStr: string, sendFlag=true) {
    try {
        pool.config = JSON.parse(configStr);
        configEmitter.emit("update", pool.config);
        if (sendFlag) {
            socket.send({ type: "updateConfig", configStr });
        }
    } catch (error) {
        console.log(error);
    }
}